package com.example.dormitorymanagement.service;

import com.example.dormitorymanagement.exception.ResourceNotFoundException;
import com.example.dormitorymanagement.model.Building;
import com.example.dormitorymanagement.repository.BuildingRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class BuildingService {

    private final BuildingRepository buildingRepository;

    @Transactional
    public Building createBuilding(Building building) {
        if (buildingRepository.existsByName(building.getName())) {
            throw new IllegalArgumentException("宿舍楼名称已存在");
        }
        return buildingRepository.save(building);
    }

    @Transactional(readOnly = true)
    public List<Building> getAllBuildings() {
        return buildingRepository.findAll();
    }

    @Transactional(readOnly = true)
    public Building getBuildingById(Integer id) {
        return buildingRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("宿舍楼不存在"));
    }

    @Transactional
    public Building updateBuilding(Integer id, Building buildingDetails) {
        Building building = getBuildingById(id);
        building.setName(buildingDetails.getName());
        building.setAddress(buildingDetails.getAddress());
        building.setFloors(buildingDetails.getFloors());
        return buildingRepository.save(building);
    }

    @Transactional
    public void deleteBuilding(Integer id) {
        Building building = getBuildingById(id);
        buildingRepository.delete(building);
    }

    @Transactional(readOnly = true)
    public List<Building> searchBuildingsByName(String name) {
        return buildingRepository.findByNameContainingIgnoreCase(name);
    }
}